package com.rep.testappinfo

import android.Manifest
import android.app.PendingIntent
import android.content.ComponentName
import android.content.Intent
import android.content.pm.*
import android.graphics.drawable.Icon
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.pm.ShortcutInfoCompat
import androidx.core.content.pm.ShortcutManagerCompat
import androidx.core.graphics.drawable.IconCompat
import androidx.fragment.app.FragmentActivity


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val list = mutableListOf<ApplicationInfo>()
        val packages = packageManager.getInstalledApplications(0)
        for (packageInfo in packages) {
            val appName = packageInfo.loadLabel(packageManager).toString()
            val packageName = packageInfo.packageName
            val appIcon = packageInfo.loadIcon(packageManager)
            val className = packageInfo.className

            if (packageInfo.flags and ApplicationInfo.FLAG_SYSTEM == 0) {
                //如果非系统应用
                list.add(packageInfo)
                Log.i("应用信息", "$appName | $packageName | $className")
            }

        }
        findViewById<View>(R.id.hi_tv).setOnClickListener {
            val launchIntent =
                packageManager.getLaunchIntentForPackage(list.random().packageName)
//            launchIntent?.let { startActivity(it) }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
                if (ShortcutManagerCompat.isRequestPinShortcutSupported(this)) {
                    val packageInfo = list.random()
                    val shortcutIntent = getIntent(packageInfo)

                    val pinShortcutInfo = ShortcutInfoCompat.Builder(
                        this@MainActivity,
                        packageInfo.loadLabel(packageManager).toString()
                    ).setShortLabel(packageInfo.loadLabel(packageManager).toString())
                        .setIcon(IconCompat.createWithResource(this, R.drawable.feedback_ic))
                        .setIntent(shortcutIntent)
                        .build()
                    val pinnedShortcutCallbackIntent = ShortcutManagerCompat.createShortcutResultIntent(this, pinShortcutInfo)

                    val successCallback = PendingIntent.getBroadcast(this, /* request code */ 0,
                        pinnedShortcutCallbackIntent, /* flags */ 0)

                    ShortcutManagerCompat.requestPinShortcut(this, pinShortcutInfo,
                        successCallback.intentSender)
                }
            } else {
                if (ContextCompat.checkSelfPermission(
                        this,
                        "com.android.launcher.permission.INSTALL_SHORTCUT"
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    // You can use the API that requires the permission.
                    ActivityCompat.requestPermissions(
                        this@MainActivity,
                        arrayOf(
                            Manifest.permission.INSTALL_SHORTCUT,
                            Manifest.permission.UNINSTALL_SHORTCUT
                        ),
                        101
                    )
                } else {
                    createShortCut(list.random())
                }


            }
        }


    }

    //创建桌面快捷方式
    private fun createShortCut(packageInfo: ApplicationInfo) {
        //创建Intent对象
        val shortcutIntent = getIntent(packageInfo)
        val resultIntent = Intent()
        // Intent.ShortcutIconResource.fromContext 这个就是设置快捷方式的图标
        resultIntent.putExtra(
            Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
            Intent.ShortcutIconResource.fromContext(
                this,
                R.drawable.feedback_ic
            )
        )
        //启动的Intent
        resultIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent)

        //这里可以设置快捷方式的名称
        resultIntent.putExtra(
            Intent.EXTRA_SHORTCUT_NAME
            , packageInfo.loadLabel(packageManager).toString()
        )

        //设置Action
        resultIntent.action = "com.android.launcher.action.INSTALL_SHORTCUT"

        //发送广播、通知系统创建桌面快捷方式
        sendBroadcast(resultIntent)
    }

    private fun getIntent(packageInfo: ApplicationInfo): Intent {
        val shortcutIntent = Intent()

        //设置点击快捷方式，进入指定的Activity
        //注意：因为是从Lanucher中启动，所以这里用到了ComponentName
        //其中new ComponentName这里的第二个参数，是Activity的全路径名，也就是包名类名要写全。
        val doStartApplicationWithPackageName =
            doStartApplicationWithPackageName(packageInfo.packageName)
        if (doStartApplicationWithPackageName != null) {
            shortcutIntent?.component = ComponentName(
                packageInfo.packageName,
                doStartApplicationWithPackageName
            )
        }

        //给Intent添加 对应的flag
        shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS or Intent.FLAG_ACTIVITY_NEW_TASK)
        return shortcutIntent
    }

    private fun doStartApplicationWithPackageName(packagename: String): String? {

        // 通过包名获取此APP详细信息，包括Activities、services、versioncode、name等等
        var packageinfo: PackageInfo? = null
        try {
            packageinfo = getPackageManager().getPackageInfo(packagename, 0)
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        if (packageinfo == null) {
            return null
        }

        // 创建一个类别为CATEGORY_LAUNCHER的该包名的Intent
        val resolveIntent = Intent(Intent.ACTION_MAIN, null)
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER)
        resolveIntent.setPackage(packageinfo.packageName)

        // 通过getPackageManager()的queryIntentActivities方法遍历
        val resolveinfoList: List<ResolveInfo> =
            packageManager.queryIntentActivities(resolveIntent, 0)
        val resolveinfo = resolveinfoList.iterator().next()
        if (resolveinfo != null) {
            // packagename = 参数packname
            val packageName = resolveinfo.activityInfo.packageName
            // 这个就是我们要找的该APP的LAUNCHER的Activity[组织形式：packagename.mainActivityname]
            return resolveinfo.activityInfo.name
        }
        return null
    }
}